from flask import Flask, render_template, Response
from flask import request
from flask_api import status
from car_base.car_drive import CarDrive
from camera.search_camera import setCamera

import json
import cv2

app = Flask(__name__)
# car_drive = CarDrive(with_flag=False)
car_drive = CarDrive(cline="uart",with_flag=False)

task_flag = ""   # 任务执行标志

@app.route('/')
def base_layout():
    return render_template('ControlCar.html')

@app.route('/AutoCar')
def auto_car():
    return render_template("AutoCar.html")

def getImage():
    cap = setCamera("0")
    # img = cv2.imread("01.jpg")
    while True:
        ret, img = cap.read()
        ret, buf = cv2.imencode(".jpeg", img)
        yield (
                b"--frame\r\nContent-Type: image/jpeg\r\n\r\n" + buf.tobytes() + b"\r\n\r\n"
        )

@app.route('/videostreamIpc/')
def videostreamIpc():
    return Response(
        getImage(), mimetype="multipart/x-mixed-replace; boundary=frame"
    )


def request_parse(request_data):
    if request_data.method == "POST":
        ret_data = request_data.get_json()
    elif request_data.method == "GET":
        ret_data = json.loads(request_data.data.decode("utf8"))
    return ret_data


@app.route('/carControl', methods=['GET', 'POST'])
def trackControl():
    ret_msg = 'ok', status.HTTP_200_OK
    data = request_parse(request)
    print("data", data)

    command_val = data.get("commandType")
    if isinstance(command_val, type(None)):
        return "commandType Can not be empty", status.HTTP_400_BAD_REQUEST

    commandSets = ['FORWARD', 'BACK', 'TURNLEFT', 'TURNRIGHT', 'STOP']
    if not command_val.upper() in commandSets:
        return 'commandType can only be [FORWARD， BACK， TURNLEFT， TURNRIGHT, STOP]', status.HTTP_400_BAD_REQUEST

    speed_val = data.get("speed")
    code_disk_val = data.get("codeDisk")
    if (isinstance(speed_val, type(None)) and isinstance(code_disk_val, type(None))):
        return "require parameters speed, codedisk", status.HTTP_400_BAD_REQUEST

    try:
        speed_val = int(speed_val) % 100
        code_disk_val = int(code_disk_val)
    except Exception as e:
        import logging
        logging.exception(e)
        return "parameter type must be integer", status.HTTP_400_BAD_REQUEST

    # 控制逻辑
    if command_val.upper() == commandSets[0]:  # 前进
        car_drive.go(speed_val, code_disk_val)
    elif command_val.upper() == commandSets[1]:
        car_drive.dow(speed_val, code_disk_val)
    elif command_val.upper() == commandSets[2]:
        car_drive.left(speed_val)
    elif command_val.upper() == commandSets[3]:
        car_drive.right(speed_val)
    elif command_val.upper() == commandSets[4]:
        car_drive.stop()
    return ret_msg

@app.route('/carTask', methods=['GET', 'POST'])
def carTask():
    global task_flag
    ret_msg = 'ok', status.HTTP_200_OK
    data = request_parse(request)
    print("data", data)

    command_val = data.get("commandType")

    task_flag = command_val.upper()

    return ret_msg

# 无人车自动行驶
def runTask():
    car = CarDrive(cline="uart")
    if task_flag == "TASK1":
        car.go(80, 350)
        car.dow(80, 350)
        car.left(90)
        car.right(90)
        car.xj(60)
    elif task_flag == "TASK2":
        pass


app.run(host="127.0.0.1", port="8080", threaded=False)
while True:
    runTask()
